package com.buddha.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buddha.api.common.Result;
import com.buddha.api.entity.Car;
import com.buddha.api.service.impl.CarServiceImpl;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mybatis-plus
 * @since 2023-07-06
 */
@CrossOrigin(origins = {"*"})
@RestController
@RequestMapping("/car")
public class CarController {

    @Resource
    CarServiceImpl carService;

    @PostMapping("/save")
    public Result AddCar(@RequestBody Car car){
        Car flagCar = carService.getById(car.getCarId());
        boolean flag;
        if(flagCar == null){
            flag = carService.InsertCar(car);
            return flag?Result.success():Result.error("300","汽车已存在");
        }else{
            carService.updateById(car);
            return Result.success();
        }
    }

    //分页信息分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String carName){
        //pageNum为起始下标
        IPage<Car> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
        //添加模糊查询条件
        queryWrapper.like("car_name",carName);
        IPage<Car> carPage = carService.page(page, queryWrapper);
        return Result.success(carPage);
    }

    // 删除
    @PostMapping("/del")
    public Result delBrand(@RequestBody String carId){
        boolean flag = carService.removeById(carId);
        return flag?Result.success():Result.error();
    }

    //分页信息分页查询
    @GetMapping("/list")
    public Result getCarList(){
        //pageNum为起始下标
        List<Car> carList = carService.list();
        return Result.success(carList);
    }

    //通过id查询汽车
    @GetMapping("/id")
    public Result getCarById(@RequestParam Integer carId){
        Car car = carService.getById(carId);
        return Result.success(car);
    }

    //通过id查询汽车
    @GetMapping("/like")
    public Result searchCar(@RequestParam String like){
        QueryWrapper<Car> carQueryWrapper = new QueryWrapper<>();
        carQueryWrapper.like("car_name",like);
        List<Car> carList = carService.list(carQueryWrapper);
        return Result.success(carList);
    }

}
